package com.phone.servlet;

import com.phone.ParameterCheck;
import com.phone.entity.PointHistory;
import com.phone.exception.ErrorCode;
import com.phone.exception.ErrorException;
import com.phone.handle.EntityHandle;
import com.phone.handle.PointHandle;
import com.phone.utils.TextUtil;
import org.hibernate.Session;
import org.json.JSONObject;

import javax.servlet.annotation.WebServlet;
import java.nio.charset.CharacterCodingException;
import java.util.Date;

/**
 * Created by tisen on 2017/9/5.
 */
@WebServlet(name = "Point",urlPatterns = "/point")
public class PointServlet extends EntityServlet<PointHistory> {

    private static final String OWNER_ID = "owner";
    private static final String TYPE = "type";
    private static final String SCORE = "score";

    @Override
    protected JSONObject otherHandle(String action, ParameterCheck check, Session session) throws Exception {
        throw new ErrorException(ErrorCode.UN_DEFINED_ACTION);
    }

    @Override
    public PointHistory getEntity(ParameterCheck check) throws Exception {
        PointHistory pointHistory = new PointHistory();
        pointHistory.setOwner(check.getParameterString(OWNER_ID, false));
        pointHistory.setType(check.getParameterInt(TYPE, false, 0));
        pointHistory.setScore(check.getParameterInt(SCORE, false, 0));
        pointHistory.setDate(new Date());
        return pointHistory;
    }

    @Override
    public PointHistory getUpdateEntity(ParameterCheck check) throws Exception {
        return null;
    }

    @Override
    public String getSearch(ParameterCheck check) throws Exception {
        String ownerid = check.getParameterString(OWNER_ID, true);
        if (TextUtil.textIsEmpty(ownerid))
            return "from PointHistory";
        else
            return "from PointHistory where owner ='" + ownerid + "'";
    }

    @Override
    public String getOwnerID(ParameterCheck check) throws Exception {
        return check.getParameterString(OWNER_ID, false);
    }

    @Override
    public EntityHandle getHandle(Session session) {
        return new PointHandle(session);
    }
}
